package com.varian.gateway.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.varian.gateway.constant.GatewayConstant;
import com.varian.tool.contant.ResultConstant;
import com.varian.tool.result.R;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author ben
 * @since 2024/12/30
 */
public class GlobalExceptionHandlerFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse originalResponse = exchange.getResponse();
        DataBufferFactory bufferFactory = originalResponse.bufferFactory();
        // 包装响应对象
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                HttpStatusCode statusCode = getStatusCode();
                if (statusCode != null && statusCode.is5xxServerError()) {
                    if (body instanceof Flux<? extends DataBuffer> fluxBody) {
                        // 读取响应体内容
                        return super.writeWith(fluxBody.map(dataBuffer -> {
                            byte[] content = new byte[dataBuffer.readableByteCount()];
                            dataBuffer.read(content);
                            DataBufferUtils.release(dataBuffer);
                            if (JSONUtil.isTypeJSONObject(StrUtil.utf8Str(content))) {
                                JSONObject json = JSONUtil.parseObj(content);
                                if (ResultConstant.FAIL_CODE.equals(json.getStr(ResultConstant.R_CODE))) {
                                    return bufferFactory.wrap(JSONUtil.toJsonStr(R.fail()).getBytes(StandardCharsets.UTF_8));
                                }
                            }
                            return bufferFactory.wrap(content);
                        }));
                    }
                }
                return super.writeWith(body);
            }
        };

        return chain.filter(exchange.mutate().response(decoratedResponse).build());
    }

    @Override
    public int getOrder() {
        return GatewayConstant.EXCEPTION_HANDLER_FILTER_ORDER;
    }
}